import env from '@/config/index.js';
class Cache {
	name = ""
	expiredKey = "_expired_time"
	// 过期时间的倍数
	expiredCount = 1000 * 60
	constructor(name) {
		this.name = name;
	}
	// 过期时间戳计算
	expiredCompute(time) {
		return time * this.expiredCount + new Date().getTime();
	}
	// 设置缓存过期时间
	setExpiredTiem(cache, key, payload, time) {
		cache[key] = new Object();
		cache[key]['data'] = payload;
		cache[key][`${key}${this.expiredKey}`] = this.expiredCompute(time)
	}
	// 是否过期
	isExpired(expiredTiem) {
		let nowTime = new Date().getTime();
		return nowTime >= expiredTiem
	}
	// 设置缓存
	set(key, payload, expiredTiem = 0) {
		let cache = this.get(this.name) || {};
		if (key == this.name) {
			cache = payload;
		} else {
			if (expiredTiem) {
				this.setExpiredTiem(cache, key, payload, expiredTiem);
			} else {
				cache[key] = payload;
			}
		}
		uni.setStorageSync(this.name, cache);
	}
	// 获取缓存
	get(key) {
		let rootCache = uni.getStorageSync(this.name);
		if (key == this.name) return rootCache;
		let cache = rootCache[key]
		if (typeof cache == 'object' && cache.hasOwnProperty(`${key}${this.expiredKey}`)) {
			if (this.isExpired(cache[`${key}${this.expiredKey}`])) {
				this.remove(key);
				delete cache['data'];
			}
			return cache['data']
		}
		return cache;
	}
	// 删除缓存
	remove(key) {
		if (this.name == key) {
			uni.removeStorageSync(this.name);
		} else {
			let cache = this.get(this.name);
			delete cache[key];
			this.set(this.name, cache)
		}
	}
}

export default new Cache(env.appName)